package com.app.shortvideo.base

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewbinding.ViewBinding
import com.app.shortvideo.R
import com.app.shortvideo.net.base.ResponseCode
import com.app.library.base.ApiException
import com.app.library.base.LibFragment
import com.app.library.base.LibViewModel
import com.app.shortvideo.Session
import com.app.library.utils.ToasterUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SizeUtils
import org.greenrobot.eventbus.EventBus

abstract class BaseFragment<VB : ViewBinding, VM : LibViewModel> : LibFragment<VB, VM>() {
    val TAG = javaClass.simpleName

    private var refreshTime = 0L
    var isRefresh = true
    var pageNum = 1
    var savedInstanceState: Bundle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.savedInstanceState = savedInstanceState
        if (isNessBus())
            EventBus.getDefault().register(this)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.root.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                val manager: InputMethodManager =
                    activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                activity?.currentFocus?.windowToken?.let {
                    manager.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            }
            false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isNessBus())
            EventBus.getDefault().unregister(this)
    }
    fun hasNet(showToast:Boolean? = false): Boolean {
        val netState = NetworkUtils.getNetworkType() != NetworkUtils.NetworkType.NETWORK_NO
        if (showToast==true&&!netState){
            ToasterUtils.showShort(getString(R.string.error_connection_toast_title))
        }
        return netState
    }
    override fun handleApiExp(exception: ApiException) {
        when (exception.code) {
            ResponseCode.INVALID_TOKEN -> {
                Session.clearSession()
            }
            ResponseCode.CODE_10000 -> {
                showToast(exception.msg ?: "")
            }
            ResponseCode.CODE_INVALID_AUTO -> {
            }
            ResponseCode.CODE_CONFIRM_TIPS -> {
            }
            else -> showToast(
                exception.msg ?: ResponseCode.getStringByCode(
                    context ?: return,
                    exception.code
                )
            )
//            else -> showToast(ResponseCode.getStringResIdByCode(exception.code))
        }
    }

    private fun showTokenExpired() {
//        if (!Session.isShowTokenDialog) {
//            Session.isShowTokenDialog = true
//            DialogUtils.showDescDialog(activity ?: return, "Token expired!") {
//                AccountEntranceActivity.start(activity ?: return@showDescDialog)
//            }.apply {
//                setCanceledOnTouchOutside(false)
//                setCancelable(false)
//            }
//        }
    }

    /**
     * 是否需要EventBus
     */
    open fun isNessBus(): Boolean {
        return false
    }


    /**
     * 初始化刷新控件
     */
    fun initRefreshView(
        refreshView: SwipeRefreshLayout,
        offsetDP: Float? = null,
        isRefresh: Boolean? = null,
        refresh: (() -> Unit)? = null
    ) {
        refreshView.setOnRefreshListener {
            refresh?.invoke()
        }
        offsetDP?.let {
            refreshView.setProgressViewOffset(true, 0, SizeUtils.dp2px(it))
        }
        isRefresh?.let {
            refreshView.isRefreshing = it
        }
        mViewModel?.refresh?.observe(this) {
            refreshView(refreshView, it)
        }
    }

    private fun refreshView(refreshView: SwipeRefreshLayout, isRefresh: Boolean) {
        if (isRefresh) {
            refreshTime = System.currentTimeMillis()
            refreshView.isRefreshing = true
        } else {
            val duration = System.currentTimeMillis() - refreshTime
            if (duration < 1000) {
                refreshView.postDelayed({
                    refreshView.isRefreshing = false
                }, 1000 - duration)
            } else {
                refreshView.isRefreshing = false
            }
        }
    }
}